package cn.gzjp.modules.logis.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import cn.gzjp.modules.gas.entity.GasRecharge;
import cn.gzjp.modules.gas.service.AliyunSms;
import cn.gzjp.modules.gas.service.GasRechargeService;
import cn.gzjp.modules.logis.entity.LogisCar;
import cn.gzjp.modules.logis.entity.LogisCarRoad;
import cn.gzjp.modules.logis.entity.LogisUser;
import cn.gzjp.modules.logis.service.LogisCarRoadService;
import cn.gzjp.modules.logis.service.LogisUserService;
import cn.hutool.core.util.StrUtil;
import com.aliyuncs.exceptions.ClientException;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import cn.gzjp.common.utils.DateUtils;
import cn.gzjp.common.utils.MyBeanUtils;
import cn.gzjp.common.persistence.Page;
import cn.gzjp.common.web.BaseController;
import cn.gzjp.common.utils.StringUtils;
import cn.gzjp.common.utils.excel.ExportExcel;
import cn.gzjp.common.utils.excel.ImportExcel;
import cn.gzjp.modules.logis.entity.LogisDelivery;
import cn.gzjp.modules.logis.service.LogisDeliveryService;

/**
 * 物流发货Controller
 * @author zengcp
 * @version 2018-03-22
 */
@Controller
@RequestMapping(value = "${adminPath}/logis/logisDelivery")
public class LogisDeliveryController extends BaseController {

	@Autowired
	private LogisDeliveryService logisDeliveryService;
	@Autowired
	private LogisUserService logisUserService;
	@Autowired
	private LogisCarRoadService logisCarRoadService;

	
	/**
	 * 物流发货列表页面
	 */
	@RequiresPermissions("logis:logisDelivery:list")
	@RequestMapping(value = {"list", ""})
	public String list(LogisDelivery logisDelivery, HttpServletRequest request, HttpServletResponse response, Model model) {
		logisDelivery.setAuditStatus("0");
		Page<LogisDelivery> page = logisDeliveryService.findPage(new Page<LogisDelivery>(request, response), logisDelivery);
		model.addAttribute("page", page);
		model.addAttribute("url", "/logis/logisDelivery/");
		return "modules/logis/logisDeliveryList";
	}

	/**
	 * 整车
	 */
	@RequiresPermissions("logis:logisDelivery:list")
	@RequestMapping(value = "wholeCar")
	public String wholeCar(LogisDelivery logisDelivery, HttpServletRequest request, HttpServletResponse response, Model model) {
		logisDelivery.setWholeCar("整车");
		logisDelivery.setAuditStatus("1");
		Page<LogisDelivery> page = logisDeliveryService.findPage(new Page<LogisDelivery>(request, response), logisDelivery);
		model.addAttribute("page", page);
		model.addAttribute("url", "/logis/logisDelivery/wholeCar");
		return "modules/logis/logisDeliveryList";
	}
	/**
	 * 零担
	 */
	@RequiresPermissions("logis:logisDelivery:list")
	@RequestMapping(value = "halfCar")
	public String halfCar(LogisDelivery logisDelivery, HttpServletRequest request, HttpServletResponse response, Model model) {
		logisDelivery.setWholeCar("零担");
		logisDelivery.setAuditStatus("1");
		Page<LogisDelivery> page = logisDeliveryService.findPage(new Page<LogisDelivery>(request, response), logisDelivery);
		model.addAttribute("page", page);
		model.addAttribute("url", "/logis/logisDelivery/halfCar");
		return "modules/logis/logisDeliveryList";
	}

	/**
	 * 查看，增加，编辑物流发货表单页面
	 */
	@RequiresPermissions(value={"logis:logisDelivery:view","logis:logisDelivery:add","logis:logisDelivery:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(LogisDelivery logisDelivery, Model model) {
		model.addAttribute("logisDelivery", logisDelivery);
		LogisUser serarch = new LogisUser();
		List<LogisUser> carrierUserList = logisUserService.findList(serarch);
		model.addAttribute("carrierUserList", carrierUserList);
		return "modules/logis/logisDeliveryForm";
	}

	/**
	 * 保存物流发货
	 */
	@RequiresPermissions(value={"logis:logisDelivery:add","logis:logisDelivery:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(LogisDelivery logisDelivery, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, logisDelivery)){
			return form(logisDelivery, model);
		}
		if(!logisDelivery.getIsNewRecord()){//编辑表单保存
			LogisDelivery t = logisDeliveryService.get(logisDelivery.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(logisDelivery, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			logisDeliveryService.save(t);//保存
		}else{//新增表单保存
			logisDeliveryService.save(logisDelivery);//保存
		}
		addMessage(redirectAttributes, "保存物流发货成功");
		return redirect("/logis/logisDelivery/");
	}
	
	/**
	 * 删除物流发货
	 */
	@RequiresPermissions("logis:logisDelivery:del")
	@RequestMapping(value = "delete")
	public String delete(LogisDelivery logisDelivery, RedirectAttributes redirectAttributes) {
		logisDeliveryService.delete(logisDelivery);
		addMessage(redirectAttributes, "删除物流发货成功");
		return redirect("/logis/logisDelivery/");
	}

	@RequestMapping(value = "viewDeliveryLogs")
	public String viewDeliveryLogs(LogisDelivery logisDelivery, Model model) {
		model.addAttribute("logisDelivery", logisDelivery);
		return "modules/logis/viewDeliveryLogs";
	}

	/**
	 * 批量删除物流发货
	 */
	@RequiresPermissions("logis:logisDelivery:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			logisDeliveryService.delete(logisDeliveryService.get(id));
		}
		addMessage(redirectAttributes, "删除物流发货成功");
		return redirect("/logis/logisDelivery/");
	}

	/**
	 * 发布
	 */
	@RequestMapping(value = "auditPass")
	public String auditPass(LogisDelivery logisDelivery, RedirectAttributes redirectAttributes) {
		if(logisDelivery.getInsuranceFee()==null){
			addMessage(redirectAttributes, "发布失败，请先设置保险费用");
			return redirect("/logis/logisDelivery/");
		}
		if(StrUtil.isBlank(logisDelivery.getEstimateWeight())){
			addMessage(redirectAttributes, "发布失败，请先设置预估重量");
			return redirect("/logis/logisDelivery/");
		}
		if(logisDelivery.getOwnerUnitPrice()==null){
			addMessage(redirectAttributes, "发布失败，请先设置运输单价(货主端)");
			return redirect("/logis/logisDelivery/");
		}
		if(logisDelivery.getOwnerUnitPrice().intValue()<logisDelivery.getDriverUnitPrice().intValue()){
			addMessage(redirectAttributes, "发布失败，货主端运费单价不能低于司机端运费单价");
			return redirect("/logis/logisDelivery/");
		}
		logisDelivery.setStatus("12");
		logisDelivery.setAuditStatus("1");//已发布
		logisDelivery.setAuditTime(new Date());
		logisDeliveryService.save(logisDelivery);

		LogisCarRoad search = new LogisCarRoad();
		search.setStartProvince(logisDelivery.getStartProvince());
		search.setEndProvince(logisDelivery.getEndProvince());
		search.setStartcity(logisDelivery.getStartCity());
		search.setEndcity(logisDelivery.getEndCity());

		List<LogisCarRoad> carRoads = logisCarRoadService.findList(search);
		List<String> mobileList = Lists.newArrayList();
		for(LogisCarRoad carRoad:carRoads){
			LogisUser user = logisUserService.get(carRoad.getOpenid());
			String mobile = user.getMobile();
			if(StringUtils.isNotBlank(mobile)&&user.isReceivePmsg()){
				mobileList.add(mobile);
			}
		}
		for(String mobile:mobileList){
			try {
				AliyunSms.sendReceivePmsg("百灵智慧物流",mobile,
						logisDelivery.getStartProvince()+logisDelivery.getStartCity(),
						logisDelivery.getEndProvince()+logisDelivery.getEndCity());
			} catch (ClientException e) {
				e.printStackTrace();
			}
		}

		addMessage(redirectAttributes, "发布成功");
		return redirect("/logis/logisDelivery/");
	}



	/**
	 * 取消接单
	 */
	@RequestMapping(value = "delCarrier")
	public String delCarrier(LogisDelivery logisDelivery, RedirectAttributes redirectAttributes) {
		if(StrUtil.isBlank(logisDelivery.getCarrier())){
			addMessage(redirectAttributes, "该订单还未有司机接单，取消失败");
			return redirect("/logis/logisDelivery/wholeCar");
		}
		int statusInt = Integer.parseInt(logisDelivery.getStatus());
		if(statusInt>=14){
			addMessage(redirectAttributes, "该订单状态为"+logisDelivery.getStatusText()+"无法取消接单，取消失败");
			return redirect("/logis/logisDelivery/wholeCar");
		}

		logisDelivery.setCarrier(null);
		logisDelivery.setStatus("12");
		logisDeliveryService.save(logisDelivery);
		addMessage(redirectAttributes, "后台取消接单成功");
		return redirect("/logis/logisDelivery/wholeCar");
	}


	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("logis:logisDelivery:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(LogisDelivery logisDelivery, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "物流发货"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<LogisDelivery> page = logisDeliveryService.findPage(new Page<LogisDelivery>(request, response, -1), logisDelivery);
    		new ExportExcel("物流发货", LogisDelivery.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出物流发货记录失败！失败信息："+e.getMessage());
		}
		return redirect("/logis/logisDelivery/?repage");
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("logis:logisDelivery:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<LogisDelivery> list = ei.getDataList(LogisDelivery.class);
			for (LogisDelivery logisDelivery : list){
				try{
					logisDeliveryService.save(logisDelivery);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条物流发货记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条物流发货记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入物流发货失败！失败信息："+e.getMessage());
		}
		return redirect("/logis/logisDelivery/?repage");
    }
	
	/**
	 * 下载导入物流发货数据模板
	 */
	@RequiresPermissions("logis:logisDelivery:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "物流发货数据导入模板.xlsx";
    		List<LogisDelivery> list = Lists.newArrayList(); 
    		new ExportExcel("物流发货数据", LogisDelivery.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return redirect("/logis/logisDelivery/?repage");
    }
	@ModelAttribute
	public LogisDelivery get(@RequestParam(required=false) String id) {
		LogisDelivery entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = logisDeliveryService.get(id);
		}
		if (entity == null){
			entity = new LogisDelivery();
		}
		return entity;
	}
	

}